package com.guiwu.gteway.industryapp.Device.MyAdapter;

import android.content.Context;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.guiwu.gteway.industryapp.Device.View.MonitorListFragment;
import com.guiwu.gteway.industryapp.Device.module.GateWay;
import com.guiwu.gteway.industryapp.Device.module.Monitor;
import com.guiwu.gteway.industryapp.Device.module.MonitorGroup;
import com.guiwu.gteway.industryapp.R;
import com.guiwu.gteway.industryapp.util.MyLog;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.guiwu.gteway.industryapp.Device.module.Monitor.BIT;

/**
 * Created by qiaoguan on 2018/3/10. 监控点的组列表
 */

public class MonitorExpandAdapter extends BaseExpandableListAdapter {

    private LayoutInflater mInflater = null;
    private Context context;
    private List<MonitorGroup> monitorGroups = new ArrayList<>();
    private GateWay gateWay;
    private static final int SWITCH = 0x00;
    private static final int EDIT_VIEW = 0x01;
    private static final int TEXT_VIEW = 0x02;

    public MonitorExpandAdapter(LayoutInflater inflater, List<MonitorGroup> monitorGroups, GateWay gateWay ,Context context){
        this.mInflater = inflater;
        this.monitorGroups = monitorGroups;
        this.context = context;
        this.gateWay = gateWay;
    }

    @Override
    public int getGroupCount() {
        return monitorGroups.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return monitorGroups.get(groupPosition).getMonitors().size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return monitorGroups.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return monitorGroups.get(groupPosition).getMonitors().get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        ViewHolderGroup holderGroup;
        if (convertView == null){
            convertView = mInflater.inflate(R.layout.groups_title_item,parent,false);
            holderGroup = new ViewHolderGroup();
            holderGroup.groupTitleView = convertView.findViewById(R.id.title_item);
            convertView.setTag(holderGroup);
        }else {
            holderGroup = (ViewHolderGroup) convertView.getTag();
        }
        String title = monitorGroups.get(groupPosition).getGroupName();
        holderGroup.groupTitleView.setText(title);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
        final ViewHolderChild holderChild;
        final Monitor monitor = monitorGroups.get(groupPosition).getMonitors().get(childPosition);
        int type = getChildType(groupPosition,childPosition);
        //view分类显示
            if (convertView == null){
                holderChild = new ViewHolderChild();
                if (type == SWITCH){
                    convertView = mInflater.inflate(R.layout.groups_child_item_sw, parent,false);
                    holderChild.childSwitch = convertView.findViewById(R.id.monitor_switch);
                    holderChild.chileName = convertView.findViewById(R.id.monitor_name_sw);
                    holderChild.EffectiveView = convertView.findViewById(R.id.monitor_worn_sw);

                    if (!monitor.isWriteable() || judgeCompetence())
                        holderChild.childSwitch.setEnabled(false);
                    if (monitor.isDataAbnormal()){
                        makeVisible(holderChild.childSwitch,holderChild.EffectiveView);
                    }
                    convertView.setTag(holderChild);

                }else if (type == EDIT_VIEW){
                    convertView = mInflater.inflate(R.layout.groups_child_item_et,parent,false);
                    holderChild.childEditText = convertView.findViewById(R.id.monitor_edit_text);
                    holderChild.chileName = convertView.findViewById(R.id.monitor_name_et);
                    holderChild.EffectiveView = convertView.findViewById(R.id.monitor_worn_et);

//                    if (!monitor.isWriteable())
//                        holderChild.childEditText.setEnabled(false);
                    if (monitor.isDataAbnormal()){
                        makeVisible(holderChild.childEditText,holderChild.EffectiveView);
                    }
                    convertView.setTag(holderChild);
                }else if (type == TEXT_VIEW){
                    convertView = mInflater.inflate(R.layout.group_child_item_tv,parent,false);
                    holderChild.childTextView = convertView.findViewById(R.id.monitor_text_view);
                    holderChild.chileName = convertView.findViewById(R.id.monitor_name_tv);
                    holderChild.EffectiveView = convertView.findViewById(R.id.monitor_worn_tv);

//                    if (!monitor.isWriteable())
//                        holderChild.childTextView.setEnabled(false);
                    if (monitor.isDataAbnormal()){
                        makeVisible(holderChild.childTextView,holderChild.EffectiveView);
                    }
                    convertView.setTag(holderChild);
                }

            }else {
                holderChild = (ViewHolderChild) convertView.getTag();
            }

            //数据逻辑处理
            if (type == EDIT_VIEW){
//                String show = "";
//                if (monitor.getDecimal()[1] == 0)
//                    show = String.valueOf((int)monitor.getValue());
//                else
//                    show = String.valueOf(monitor.getValue());
                if (judgeCompetence()){ // 权限足够
                    MyLog.i("测试", monitor.getName()+ ":重复次数 ： " + monitor.getRepeatTime() + "  返回状态" + monitor.getValue() + "显示情况" + holderChild.childEditText.getText());
//                int returnInt = checkInput(holderChild.childEditText.getText().toString(),monitor.getDecimal(),monitor.getMax());
//                int show = checkInput(holderChild.childEditText.getText().toString(),monitor.getDecimal(),monitor.getMax());
                    if (!holderChild.childEditText.getText().toString().equals(monitor.getValue())
                            && monitor.getRepeatTime() != 0) {  //用户编辑了但是返回数值不一样
                        if (editRepeatListener != null){
                            int value = checkInput(holderChild.childEditText.getText().toString(),monitor.getDecimal(),monitor.getMax());
                            MyLog.i("测试", monitor.getName()+ "状态不正确，重发 ： " + monitor.getRepeatTime() + "重发 " +holderChild.childEditText.getText() + "重发值：" + value);
                            editRepeatListener.onRepeat(monitor,value);
                        }
                    }else {
                        monitor.resetRepeatTime();
                        holderChild.childEditText.setText(monitor.getValue());
                        MyLog.i("测试", monitor.getName()+ "状态正确执行adapter ： " + monitor.getRepeatTime());

                    }

                    holderChild.childEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                        @Override
                        public void onFocusChange(View v, boolean hasFocus) {
                            if (hasFocus)
                                if (clickListener != null){
                                    clickListener.onEditStart(monitor);
                                }
                        }
                    });

                    holderChild.childEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                        @Override
                        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                            int input =  checkInput(v.getText().toString(),monitor.getDecimal(),monitor.getMax());
                            //   monitor.setValue(input);
                            //     holderChild.childEditText.setEnabled(false);
                            if (clickListener != null){
                                clickListener.onEditFinish(monitor,input);
                                monitor.repeat();
                            }
                            MyLog.i("测试", monitor.getName() + "用户输入完毕：" + v.getText().toString() + "重发值" + input);
                            holderChild.childEditText.setText(monitor.getTypeValue(input));
                            holderChild.childEditText.clearFocus();
                            return false;
                        }
                    });
                }else {
                    holderChild.childEditText.setFocusable(false);
                    holderChild.childEditText.setFocusableInTouchMode(false);
                    holderChild.childEditText.setText(monitor.getValue());
                }
            }else if (type == SWITCH){
                if (monitor.isWriteable() && judgeCompetence()){  //可写 并且权限足够
                    boolean showCheck;
                    // MyLog.i("测试", monitor.getName()+ ":重复次数 ： " + monitor.getRepeatTime() + "返回状态" + monitor.getSwitchState() + "显示状态" + holderChild.childSwitch.isChecked());
                    if(monitor.getSwitchState() != holderChild.childSwitch.isChecked()
                            && monitor.getRepeatTime() != 0){ //用户点击了，并且第二次返回的数据不一样
                        //  MyLog.i("测试", monitor.getName()+ ":执行adapter ： " + monitor.getRepeatTime() + "返回状态" + monitor.getSwitchState());

                        if (switchRepeatListener != null){
                            switchRepeatListener.onRepeat(monitor);
                        }
                    }else {                                   //用户点击了，并且第二次返回的数据一样

                        monitor.resetRepeatTime();
                        holderChild.childSwitch.setEnabled(true);
                        //           MyLog.i("测试", monitor.getName()+ "状态正确执行adapter ： " + monitor.getRepeatTime());
                        holderChild.childSwitch.setChecked(monitor.getSwitchState());
                    }

//                if (!monitor.isSwitchCanControl()){
//                    holderChild.childSwitch.setEnabled(false);
//                }else {
//                    holderChild.childSwitch.setEnabled(true);
//                }

                    holderChild.childSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            //状态改变，不管用户有没有点击
                            //   isChange = true;
                        }
                    });

                    //点击事件
                    holderChild.childSwitch.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            holderChild.childSwitch.setEnabled(false);
                            if (clickListener != null){
                                clickListener.onSwitch(monitor,((Switch)v).isChecked());
                                //    monitor.setSwitchCanControl(false);
                                monitor.repeat();
                                //  MyLog.i("测试", monitor.getName() + "用户点击 切换" + ((Switch)v).isChecked());
                            }
                        }
                    });
                }else { //只读
                    holderChild.childSwitch.setEnabled(false);
                    holderChild.childSwitch.setChecked(monitor.getSwitchState());
                }
            }else if (type == TEXT_VIEW){
                holderChild.childTextView.setText(monitor.getValue());
            }
            if (monitor.getName()!= null)
                holderChild.chileName.setText(monitor.getName());

        return convertView;
    }

    //权限
    private boolean judgeCompetence(){
        if (gateWay.getCompetence() == 4){
            return false;
        }else
            return true;
    }

    //数据异常方法
    private void makeVisible(View goneView ,View showView){
        goneView.setVisibility(View.GONE);
        showView.setVisibility(View.VISIBLE);
    }


    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return false;
    }

    class ViewHolderGroup {
        TextView groupTitleView;
        //  ImageView expandMoreArrow;
    }

    class ViewHolderChild {
        TextView chileName;
        TextView childTextView;
        EditText childEditText;
        Switch childSwitch;
        ImageView EffectiveView;//数据是否有效
    }


    @Override
    public int getChildType(int groupPosition, int childPosition) {
        Monitor monitor = monitorGroups.get(groupPosition).getMonitors().get(childPosition);
        if (monitor.getMonitorType() == BIT)
            return SWITCH;
        else if (monitor.isWriteable()){
            return EDIT_VIEW;
        }else
            return TEXT_VIEW;

//        switch (monitor.getMonitorType()){
//            case BIT:
//                return SWITCH;
//            case BIT16:
//                return TEXT_VIEW;
//            case BIT32:
//                return EDIT_VIEW;
//            default:
//                return 1;
//        }
    }

    @Override
    public int getChildTypeCount() {
        return 3;
    }


    public List<MonitorGroup> getMonitorGroups(){
        return this.monitorGroups;
    }


    //监控点信息变化通知
    public interface OnMonitorClickListener{
        void onSwitch(Monitor monitor ,boolean coil);
        void onEditStart(Monitor monitor);
        void onEditFinish(Monitor monitor , int value);
    }

    private OnMonitorClickListener clickListener;

    public void setOnMonitorClickListener(OnMonitorClickListener clickListener){
        this.clickListener = clickListener;
    }


    //将输入抽取成int
    private int checkInput(String input,int[] bit,int max){
        if (input.equals(""))
            return 0;
        int intIn = 0;
        String patternStr = "([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])";
        Pattern r = Pattern.compile(patternStr);
        Matcher m = r.matcher(input);
        String trunStr = "0";
        if (m.find()){
            trunStr = m.group();
        }else {
            Toast.makeText(context ,"输入数据格式错误", Toast.LENGTH_SHORT).show();
        }
        try {
            float in = Float.parseFloat(trunStr);
            intIn = (int)(in * (Math.pow(10,bit[1])));
            if (intIn > max){
                Toast.makeText(context,"数据超限" ,Toast.LENGTH_SHORT).show();
                return max;
            }
        } catch (NumberFormatException e) {
            Toast.makeText(context ,"输入数据格式错误", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        return intIn;
    }

//    private String inputToSendInt(String input , int[] bit ,int max){
//
//    }

    //重发开关通知
    public interface OnSwitchRepeatListener {
        void onRepeat(Monitor monitor);
    }
    private OnSwitchRepeatListener switchRepeatListener;
    public void setOnSwitchRepeatListener(OnSwitchRepeatListener repeatListener){
        this.switchRepeatListener = repeatListener;
    }

    //重发编辑通知
    public interface OnEditRepeatListener {
        void onRepeat(Monitor monitor,int value);
    }
    private OnEditRepeatListener editRepeatListener;
    public void setOnEditRepeatListener(OnEditRepeatListener repeatListener){
        this.editRepeatListener = repeatListener;
    }
}



